package com.aiapphub.SystemCode.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Dify 消息服务
 * 基于 Dify API 实现消息的保存、获取、删除等功能
 */
@Slf4j
@Service
public class DifyMessageService {
    
    @Value("${dify.api.key:}")
    private String difyApiKey;
    
    @Value("${dify.api.url:}")
    private String difyApiUrl;
    
    private OkHttpClient httpClient;

    @Resource
    private UserService userService;
    
    @PostConstruct
    public void init() {
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        
        if (difyApiKey != null && !difyApiKey.trim().isEmpty() &&
            difyApiUrl != null && !difyApiUrl.trim().isEmpty()) {
            log.info("Dify消息服务初始化成功");
        } else {
            log.warn("Dify API密钥或连接地址未配置，消息服务未初始化");
        }
    }
    
    /**
     * 获取会话消息列表
     * @param conversationId 会话ID
     * @param userId 用户ID
     * @param limit 返回数量限制
     * @param apiKey 使用的 API Key（如果为 null，则使用默认配置的 apiKey）
     * @return 消息列表
     */
    public List<Map<String, Object>> getMessagesByConversationId(String conversationId, String userId, Integer limit, String apiKey) {
        return getMessagesByConversationId(conversationId, userId, limit, apiKey, null);
    }
    
    /**
     * 获取会话消息列表
     * @param conversationId 会话ID
     * @param userId 用户ID
     * @param limit 返回数量限制
     * @param apiKey 使用的 API Key（如果为 null，则使用默认配置的 apiKey）
     * @param apiBaseUrl API基础URL（如果为 null，则使用默认配置的 difyApiUrl）
     * @return 消息列表
     */
    public List<Map<String, Object>> getMessagesByConversationId(String conversationId, String userId, Integer limit, String apiKey, String apiBaseUrl) {
        try {
            // 如果传入了 apiKey，使用传入的；否则使用默认配置的
            String actualApiKey = (apiKey != null && !apiKey.trim().isEmpty()) ? apiKey : difyApiKey;
            
            if (actualApiKey == null || actualApiKey.trim().isEmpty()) {
                log.error("Dify API密钥未配置");
                throw new RuntimeException("Dify API密钥未配置");
            }
            
            // 如果传入了 apiBaseUrl，使用传入的；否则使用默认配置的
            String actualApiUrl = (apiBaseUrl != null && !apiBaseUrl.trim().isEmpty()) ? apiBaseUrl : difyApiUrl;
            
            if (actualApiUrl == null || actualApiUrl.trim().isEmpty()) {
                log.error("Dify API地址未配置");
                throw new RuntimeException("Dify API地址未配置");
            }
            
            String userId1 = userService.getCurrentUserId();
            System.out.println("conversationId=========================="+conversationId);
            String url = actualApiUrl + "/messages?conversation_id=" + conversationId + 
                        "&user=" + userId1 + "&limit=" + (limit != null ? limit : 20);
            System.out.println("url=========================="+url);
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .addHeader("Authorization", "Bearer " + actualApiKey)
                    .addHeader("Content-Type", "application/json")
                    .build();
            
            try (Response response = httpClient.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    log.info("获取消息列表成功，响应: {}", responseBody);
                    
                    JSONObject jsonResponse = JSON.parseObject(responseBody);
                    JSONArray dataArray = jsonResponse.getJSONArray("data");
                    
                    List<Map<String, Object>> messages = new ArrayList<>();
                    if (dataArray != null) {
                        for (int i = 0; i < dataArray.size(); i++) {
                            JSONObject message = dataArray.getJSONObject(i);
                            Map<String, Object> msgMap = new HashMap<>();
                            
                            // 安全处理基本字段
                            msgMap.put("id", message.getString("id"));
                            msgMap.put("conversation_id", message.getString("conversation_id"));
                            msgMap.put("query", message.getString("query"));
                            msgMap.put("answer", message.getString("answer"));
                            
                            // 安全处理feedback字段
                            try {
                                if (message.containsKey("feedback") && message.get("feedback") != null) {
                                    msgMap.put("feedback", message.getJSONObject("feedback"));
                                } else {
                                    msgMap.put("feedback", null);
                                }
                            } catch (Exception e) {
                                log.warn("解析feedback字段失败: {}", e.getMessage());
                                msgMap.put("feedback", null);
                            }
                            
                            // 安全处理agent_thoughts字段
                            try {
                                msgMap.put("agent_thoughts", message.get("agent_thoughts"));
                            } catch (Exception e) {
                                log.warn("解析agent_thoughts字段失败: {}", e.getMessage());
                                msgMap.put("agent_thoughts", null);
                            }
                            
                            // 安全处理message_files字段
                            try {
                                if (message.containsKey("message_files") && message.get("message_files") != null) {
                                    msgMap.put("message_files", message.getJSONArray("message_files"));
                                } else {
                                    msgMap.put("message_files", null);
                                }
                            } catch (Exception e) {
                                log.warn("解析message_files字段失败: {}", e.getMessage());
                                msgMap.put("message_files", null);
                            }
                            
                            // 安全处理时间字段
                            try {
                                msgMap.put("created_at", message.getLong("created_at"));
                            } catch (Exception e) {
                                log.warn("解析created_at字段失败: {}", e.getMessage());
                                msgMap.put("created_at", 0L);
                            }
                            
                            try {
                                msgMap.put("updated_at", message.getLong("updated_at"));
                            } catch (Exception e) {
                                log.warn("解析updated_at字段失败: {}", e.getMessage());
                                msgMap.put("updated_at", 0L);
                            }
                            messages.add(msgMap);
                        }
                    }
                    
                    return messages;
                } else {
                    String errorBody = response.body() != null ? response.body().string() : "Unknown error";
                    log.error("获取消息列表失败，状态码: {}, 错误信息: {}, 会话ID: {}", response.code(), errorBody, conversationId);
                    
                    // 根据HTTP状态码提供更具体的错误信息
                    String errorMessage;
                    if (response.code() == 404) {
                        errorMessage = "会话不存在，会话ID: " + conversationId + "。可能该会话已被删除或不存在。";
                    } else if (response.code() == 401) {
                        errorMessage = "API认证失败，请检查Dify API密钥配置";
                    } else if (response.code() == 403) {
                        errorMessage = "API访问被拒绝，请检查权限配置";
                    } else {
                        errorMessage = "获取消息列表失败: " + errorBody;
                    }
                    
                    throw new RuntimeException(errorMessage);
                }
            }
            
        } catch (IOException e) {
            log.error("获取消息列表异常", e);
            throw new RuntimeException("获取消息列表失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 获取消息详情
     * @param messageId 消息ID
     * @param userId 用户ID
     * @return 消息详情
     */
    public Map<String, Object> getMessageById(String messageId, String userId) {
        try {
            if (difyApiKey == null || difyApiKey.trim().isEmpty()) {
                log.error("Dify API密钥未配置");
                throw new RuntimeException("Dify API密钥未配置");
            }
            
            String url = difyApiUrl + "/messages/" + messageId + "?user=" + userId;
            
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .addHeader("Authorization", "Bearer " + difyApiKey)
                    .addHeader("Content-Type", "application/json")
                    .build();
            
            try (Response response = httpClient.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    log.info("获取消息详情成功，响应: {}", responseBody);
                    
                    JSONObject jsonResponse = JSON.parseObject(responseBody);
                    Map<String, Object> message = new HashMap<>();
                    message.put("id", jsonResponse.getString("id"));
                    message.put("conversation_id", jsonResponse.getString("conversation_id"));
                    message.put("query", jsonResponse.getString("query"));
                    message.put("answer", jsonResponse.getString("answer"));
                    message.put("feedback", jsonResponse.getJSONObject("feedback"));
                    message.put("agent_thoughts", jsonResponse.get("agent_thoughts"));
                    message.put("message_files", jsonResponse.getJSONArray("message_files"));
                    message.put("created_at", jsonResponse.getLong("created_at"));
                    message.put("updated_at", jsonResponse.getLong("updated_at"));
                    
                    return message;
                } else {
                    String errorBody = response.body() != null ? response.body().string() : "Unknown error";
                    log.error("获取消息详情失败，状态码: {}, 错误信息: {}", response.code(), errorBody);
                    throw new RuntimeException("获取消息详情失败: " + errorBody);
                }
            }
            
        } catch (IOException e) {
            log.error("获取消息详情异常", e);
            throw new RuntimeException("获取消息详情失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 删除消息
     * @param messageId 消息ID
     * @param userId 用户ID
     * @return 删除结果
     */
    public boolean deleteMessage(String messageId, String userId) {
        try {
            if (difyApiKey == null || difyApiKey.trim().isEmpty()) {
                log.error("Dify API密钥未配置");
                throw new RuntimeException("Dify API密钥未配置");
            }
            
            String url = difyApiUrl + "/messages/" + messageId;
            
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("user", userId);
            
            String jsonBody = JSON.toJSONString(requestBody);
            RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8"));
            
            Request request = new Request.Builder()
                    .url(url)
                    .delete(body)
                    .addHeader("Authorization", "Bearer " + difyApiKey)
                    .addHeader("Content-Type", "application/json")
                    .build();
            
            try (Response response = httpClient.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    log.info("删除消息成功，消息ID: {}", messageId);
                    return true;
                } else {
                    String errorBody = response.body() != null ? response.body().string() : "Unknown error";
                    log.error("删除消息失败，状态码: {}, 错误信息: {}", response.code(), errorBody);
                    return false;
                }
            }
            
        } catch (IOException e) {
            log.error("删除消息异常", e);
            throw new RuntimeException("删除消息失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 给消息添加反馈
     * @param messageId 消息ID
     * @param userId 用户ID
     * @param rating 评分 (like/dislike)
     * @param comment 评论
     * @return 反馈结果
     */
    public boolean addMessageFeedback(String messageId, String userId, String rating, String comment) {
        try {
            if (difyApiKey == null || difyApiKey.trim().isEmpty()) {
                log.error("Dify API密钥未配置");
                throw new RuntimeException("Dify API密钥未配置");
            }
            
            String url = difyApiUrl + "/messages/" + messageId + "/feedbacks";
            
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("user", userId);
            requestBody.put("rating", rating);
            if (comment != null && !comment.trim().isEmpty()) {
                requestBody.put("comment", comment);
            }
            
            String jsonBody = JSON.toJSONString(requestBody);
            RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8"));
            
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Authorization", "Bearer " + difyApiKey)
                    .addHeader("Content-Type", "application/json")
                    .build();
            
            try (Response response = httpClient.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    log.info("添加消息反馈成功，消息ID: {}, 评分: {}", messageId, rating);
                    return true;
                } else {
                    String errorBody = response.body() != null ? response.body().string() : "Unknown error";
                    log.error("添加消息反馈失败，状态码: {}, 错误信息: {}", response.code(), errorBody);
                    return false;
                }
            }
            
        } catch (IOException e) {
            log.error("添加消息反馈异常", e);
            throw new RuntimeException("添加消息反馈失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 获取消息反馈
     * @param messageId 消息ID
     * @param userId 用户ID
     * @return 消息反馈
     */
    public Map<String, Object> getMessageFeedback(String messageId, String userId) {
        try {
            if (difyApiKey == null || difyApiKey.trim().isEmpty()) {
                log.error("Dify API密钥未配置");
                throw new RuntimeException("Dify API密钥未配置");
            }
            
            String url = difyApiUrl + "/messages/" + messageId + "/feedbacks?user=" + userId;
            
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .addHeader("Authorization", "Bearer " + difyApiKey)
                    .addHeader("Content-Type", "application/json")
                    .build();
            
            try (Response response = httpClient.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    log.info("获取消息反馈成功，响应: {}", responseBody);
                    
                    JSONObject jsonResponse = JSON.parseObject(responseBody);
                    Map<String, Object> feedback = new HashMap<>();
                    feedback.put("rating", jsonResponse.getString("rating"));
                    feedback.put("comment", jsonResponse.getString("comment"));
                    feedback.put("created_at", jsonResponse.getLong("created_at"));
                    
                    return feedback;
                } else {
                    String errorBody = response.body() != null ? response.body().string() : "Unknown error";
                    log.error("获取消息反馈失败，状态码: {}, 错误信息: {}", response.code(), errorBody);
                    throw new RuntimeException("获取消息反馈失败: " + errorBody);
                }
            }
            
        } catch (IOException e) {
            log.error("获取消息反馈异常", e);
            throw new RuntimeException("获取消息反馈失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 停止消息生成
     * @param taskId 任务ID
     * @param userId 用户ID
     * @param apiKey 使用的 API Key（如果为 null，则使用默认配置的 apiKey）
     * @return 停止结果
     */
    public boolean stopMessageGeneration(String taskId, String userId, String apiKey) {
        try {
            // 如果传入了 apiKey，使用传入的；否则使用默认配置的
            String actualApiKey = (apiKey != null && !apiKey.trim().isEmpty()) ? apiKey : difyApiKey;
            
            if (actualApiKey == null || actualApiKey.trim().isEmpty()) {
                log.error("Dify API密钥未配置");
                throw new RuntimeException("Dify API密钥未配置");
            }
            
            String url = difyApiUrl + "/chat-messages/" + taskId + "/stop";
            
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("user", userId);
            
            String jsonBody = JSON.toJSONString(requestBody);
            RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8"));
            
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Authorization", "Bearer " + actualApiKey)
                    .addHeader("Content-Type", "application/json")
                    .build();
            
            try (Response response = httpClient.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    log.info("停止消息生成成功，任务ID: {}", taskId);
                    return true;
                } else {
                    String errorBody = response.body() != null ? response.body().string() : "Unknown error";
                    log.error("停止消息生成失败，状态码: {}, 错误信息: {}", response.code(), errorBody);
                    return false;
                }
            }
            
        } catch (IOException e) {
            log.error("停止消息生成异常", e);
            throw new RuntimeException("停止消息生成失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 获取消息建议
     * @param messageId 消息ID
     * @param userId 用户ID
     * @param apiKey 使用的 API Key（如果为 null，则使用默认配置的 apiKey）
     * @return 消息建议列表
     */
    public List<String> getMessageSuggestions(String messageId, String userId, String apiKey) {
        try {
            // 如果传入了 apiKey，使用传入的；否则使用默认配置的
            String actualApiKey = (apiKey != null && !apiKey.trim().isEmpty()) ? apiKey : difyApiKey;
            
            if (actualApiKey == null || actualApiKey.trim().isEmpty()) {
                log.error("Dify API密钥未配置");
                throw new RuntimeException("Dify API密钥未配置");
            }
            
            String url = difyApiUrl + "/messages/" + messageId + "/suggestions?user=" + userId;
            
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .addHeader("Authorization", "Bearer " + actualApiKey)
                    .addHeader("Content-Type", "application/json")
                    .build();
            
            try (Response response = httpClient.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    log.info("获取消息建议成功，响应: {}", responseBody);
                    
                    JSONObject jsonResponse = JSON.parseObject(responseBody);
                    JSONArray suggestionsArray = jsonResponse.getJSONArray("suggestions");
                    
                    List<String> suggestions = new ArrayList<>();
                    if (suggestionsArray != null) {
                        for (int i = 0; i < suggestionsArray.size(); i++) {
                            suggestions.add(suggestionsArray.getString(i));
                        }
                    }
                    
                    return suggestions;
                } else {
                    String errorBody = response.body() != null ? response.body().string() : "Unknown error";
                    log.error("获取消息建议失败，状态码: {}, 错误信息: {}", response.code(), errorBody);
                    throw new RuntimeException("获取消息建议失败: " + errorBody);
                }
            }
            
        } catch (IOException e) {
            log.error("获取消息建议异常", e);
            throw new RuntimeException("获取消息建议失败: " + e.getMessage(), e);
        }
    }
}
